package net.xdclass.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppMergePayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapMergePayRequest;
import com.alipay.api.response.AlipayTradeAppMergePayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapMergePayResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.AlipayConfig;
import net.xdclass.config.PayUrlConfig;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.ClientType;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.request.ConfirmOrderRequest;
import net.xdclass.request.RepayOrderRequest;
import net.xdclass.service.ProductOrderService;
import net.xdclass.until.CommonUtil;
import net.xdclass.until.JsonData;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2022-02-22
 */
@Slf4j
@Api("订单模块")
@RestController
@RequestMapping("/api/order/v1")
public class ProductOrderController {
    @Autowired
    private ProductOrderService productOrderService;
    @Autowired
    private PayUrlConfig payUrlConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation("获取提交订单令牌")
    @GetMapping("get_token")
    public JsonData getOrderToken() {
        LoginUser loginUser = LoginInterceptor.loginUserThreadLocal.get();
        String key = String.format(CacheKey.SUBMIT_ORDER_TOKEN_KEY, loginUser.getId());
        String token = CommonUtil.getStringNumRandom(32);
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.MINUTES);
        return JsonData .buildSuccess(token);
    }


    @ApiOperation("分页查询我的订单列表")
    @GetMapping("page")
    public JsonData pageOrderList(
            @ApiParam("当前页数") @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam("每页多少条") @RequestParam(value = "size", defaultValue = "20") int size,
            @ApiParam("订单状态") @RequestParam(value = "state", required = false) String state) {
        Map<String, Object> pageResult = productOrderService.page(page, size, state);

        return JsonData.buildSuccess(pageResult);
    }

    @ApiOperation("查询订单状态")
    @GetMapping("query_state")
    public JsonData queryProductOrderState(@ApiParam("订单号") @RequestParam("out_trade_no") String outTradeNo) {
        String state = productOrderService.queryProductOrderState(outTradeNo);
        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
    }

    @ApiOperation("提交订单")
    @PostMapping("confirm")
    public void confirmOrder(@ApiParam("订单对象")
                             @RequestBody ConfirmOrderRequest orderRequest,
                             HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(orderRequest);
        if (jsonData.getCode() == 0) {
            String clientType = orderRequest.getClientType();
            String payType = orderRequest.getPayType();
            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
                log.info("创建支付宝订单成功");
                if (clientType.equalsIgnoreCase(ClientType.H5.name())) {
                    witeData(response, jsonData);
                } else if (clientType.equalsIgnoreCase(ClientType.APP.name())) {
                    //TODO app
                }

            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT.name())) {
                //TODO 微信支付
            }
        } else {
            log.error("创建订单失败{}", jsonData.toString());
            CommonUtil.sendJsonMessage(response, jsonData);
        }
    }


    @ApiOperation("重新支付订单")
    @PostMapping("repay")
    public void repay(@ApiParam("订单对象")
                      @RequestBody RepayOrderRequest repayOrderRequest,
                      HttpServletResponse response) {
        JsonData jsonData = productOrderService.repay(repayOrderRequest);
        if (jsonData.getCode() == 0) {
            String clientType = repayOrderRequest.getClientType();
            String payType = repayOrderRequest.getPayType();
            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
                log.info("创建支付宝订单成功");
                if (clientType.equalsIgnoreCase(ClientType.H5.name())) {
                    witeData(response, jsonData);
                } else if (clientType.equalsIgnoreCase(ClientType.APP.name())) {
                    //TODO app
                }

            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT.name())) {
                //TODO 微信支付
            }
        } else {
            log.error("创建订单失败{}", jsonData.toString());
            CommonUtil.sendJsonMessage(response, jsonData);
        }
    }


    private void witeData(HttpServletResponse response, JsonData jsonData) {
        try {
            response.setContentType("text/html;charset=UTF8");
            response.getWriter().write(jsonData.getData().toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            log.error("写出html异常:{}", e);
        }
    }

    /**
     * 测试支付方法
     * 商家信息
     * 商家账号vmnsbk0042@sandbox.com
     * 登录密码111111
     * 商户PID2088621958007026
     * 账户余额
     * 111.99充值取现
     * 买家信息
     * 买家账号fohjfs4958@sandbox.com
     * 登录密码111111
     * 支付密码111111
     * 用户UID2088622958029441
     * 用户名称fohjfs4958
     * 证件类型身份证(IDENTITY_CARD)
     * 证件号码242758199104091374
     * 账户余额
     * 99887.01充值取现
     */
    @GetMapping("test_pay")
    public void testAlipay(HttpServletResponse response) throws AlipayApiException, IOException {
        HashMap<String, String> content = new HashMap<>();
        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        String no = UUID.randomUUID().toString();
        log.info("订单号:{}", no);
        content.put("out_trade_no", no);
        content.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //订单总金额，单位为元，精确到小数点后两位
        content.put("total_amount", String.valueOf("111.99"));
        //商品标题/交易标题/订单标题/订单关键字等。 注意：不可使用特殊字符，如 /，=，&amp; 等。
        content.put("subject", "杯子");
        //商品描述，可空
        content.put("body", "好的杯子");
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        content.put("timeout_express", "5m");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setBizContent(JSON.toJSONString(content));
        request.setNotifyUrl(payUrlConfig.getCallbackUrl());
        request.setReturnUrl(payUrlConfig.getAlipaySuccessReturnUrl());

        AlipayTradePagePayResponse alipayResponse = AlipayConfig.getInstance().pageExecute(request);

        if (alipayResponse.isSuccess()) {
            System.out.println("调用成功");
            String body = alipayResponse.getBody();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(body);
            response.getWriter().flush();
            response.getWriter().close();
        } else {
            System.out.println("调用失败");
        }
    }


}

